import request from "../request"
import axios from "axios"
import {v4 as uuidv4} from "uuid"
import {useConvert} from "@/hook/useConvert"
import { useStore } from "vuex"
import _ from "lodash"
import OSS from 'ali-oss'

const checkFileExist = async (url:string)=>{

  return request.post("/ossFile/checkFileExist",{
    key:url
  })

}
const ossParameter = async ()=>{

  return request.post("/ossFile/ossParameter",{
  })

}


const getPostObjectParams = () => {
  return request.post("/ossFile/getPostObjectParams")
}
const getFileMangePostObjectParams = () => {
  return request.post("/ossFile/getFileMangePostObjectParams")
}

interface UploadAuthorityFile {
  /**
   * 文件地址
   */
  path: string;

  file:File,
  /**
   * 成功返回的回调函数
   */
  successCallback?: (result: any) => void;
  /**
   * 失败的回调函数
   */
  errCallBack?: (result: any)=> void;
  /**
   * 结束的回调函数（调用成功、失败都会执行）
   */
  progressCallback?: (result: any)=> void;
}

const uploadAuthorityFile = async (options:UploadAuthorityFile)=>{
  console.log(options);
  
  let fileName = options.file.name

  let res = await getPostObjectParams();
  let obj = res.data

  console.log("obj",obj)

  let config = {} as any
  config.host = obj['host']
  config.policyBase64 = obj['policy']
  config.accessid = obj['accessKeyId']
  config.signature = obj['signature']
  config.expire = parseInt(obj['expire'])
  let fd = new FormData()


  if(_.isEmpty(options.path)){
    options.path = "authorityFile/";
  }
  let  key =  options.path + fileName
  fd.append('key', key)
  fd.append('success_action_status', '200')
  fd.append('x-oss-object-acl', 'public-read')
  fd.append('x-oss-meta-fullname', fileName)
  fd.append('OSSAccessKeyId', config.accessid)
  fd.append('policy', config.policyBase64)
  fd.append('signature', config.signature)
  fd.append('success_action_status', '200')
  fd.append('file', options.file)
  // fd.append('Content-Disposition','attachment')
  if (config.host.indexOf('http:') > -1) {
    var protocol = window.location.protocol || 'http:'
    var subUrl = config.host.substring(5, config.host.length)
    config.host = protocol + subUrl
  }
  // 数据组装完成后，发送上传请求到阿里云oss
  axios.request({
    url: config.host,
    method: 'POST',
    data: fd,
    // 这里，我们可以做上传经度
    onUploadProgress: (progressEvent:any)=> {

      (options as any).progressCallback({
        percent: progressEvent
      })

      if (progressEvent.lengthComputable) {
        let percent = (progressEvent.loaded / progressEvent.total) * 100 || 0;
        (options as any).progressCallback({
          percent: percent
        })
      }
    }
  })
    .then(() => {
    // 拿到结果后，做其他操作
      let size = options.file.size > 1000000 ? (options.file.size / 1000000).toFixed(2) + 'M' : (options.file.size / 1000).toFixed(2) + 'KB';
      (options as any).successCallback({
        attachment: fileName,
        aliyunAddress: key,
        size: size,
        host: config.host
      })
    })
    .catch(err => {
      (options as any).errCallBack(err)
    }).catch(err => {
      (options as any).errCallBack(err)
})


 
}

const upload = async (projectId:string,path = '',file:File,successCallback = new Function(), errCallBack = new Function(), progressCallback = new Function()) => {
  let fileName = file.name
  
  let res = await getFileMangePostObjectParams();
  let obj = res.data

  console.log("obj",obj)

  let config = {} as any
  config.host = obj['host']
  config.policyBase64 = obj['policy']
  config.accessid = obj['accessKeyId']
  config.signature = obj['signature']
  config.expire = parseInt(obj['expire'])
  let fd = new FormData()


  if(_.isEmpty(path)){
    path = "/";
  }
  let  key = projectId + path + fileName
  fd.append('key', key)
  fd.append('success_action_status', '200')
  fd.append('x-oss-object-acl', 'public-read')
  fd.append('x-oss-meta-fullname', fileName)
  fd.append('OSSAccessKeyId', config.accessid)
  fd.append('policy', config.policyBase64)
  fd.append('signature', config.signature)
  fd.append('success_action_status', '200')
  fd.append('file', file)
  if (config.host.indexOf('http:') > -1) {
    var protocol = window.location.protocol || 'http:'
    var subUrl = config.host.substring(5, config.host.length)
    config.host = protocol + subUrl
  }
  // 数据组装完成后，发送上传请求到阿里云oss
  axios.request({
    url: config.host,
    method: 'POST',
    data: fd,
    // 这里，我们可以做上传经度
    onUploadProgress: function(progressEvent:any) {

      progressCallback({
        percent: progressEvent
      })

      if (progressEvent.lengthComputable) {
        let percent = (progressEvent.loaded / progressEvent.total) * 100 || 0
        progressCallback({
          percent: percent
        })
      }
    }
  })
    .then(() => {
    // 拿到结果后，做其他操作
      let size = file.size > 1000000 ? (file.size / 1000000).toFixed(2) + 'M' : (file.size / 1000).toFixed(2) + 'KB'
      successCallback({
        attachment: fileName,
        aliyunAddress: key,
        size: size,
        host: config.host
      })
    })
    .catch(err => {
      errCallBack(err)
    }).catch(err => {
  errCallBack(err)
})


}



const uploadImage = async (file:File,successCallback = new Function(), errCallBack = new Function(), progressCallback = new Function(), dir = 'image') => {
  let fileName = file.name
  
  let res = await getPostObjectParams();
  let obj = res.data

  console.log("obj",obj)

  let config = {} as any
  config.host = obj['host']
  config.policyBase64 = obj['policy']
  config.accessid = obj['accessKeyId']
  config.signature = obj['signature']
  config.expire = parseInt(obj['expire'])
  let fd = new FormData(),
    uuid = uuidv4(),
    key = dir + "/" + uuid + "." + useConvert().fileName2suffix(fileName)
  fd.append('key', key)
  fd.append('success_action_status', '200')
  fd.append('x-oss-object-acl', 'public-read')
  fd.append('x-oss-meta-fullname', fileName)
  fd.append('OSSAccessKeyId', config.accessid)
  fd.append('policy', config.policyBase64)
  fd.append('signature', config.signature)
  fd.append('success_action_status', '200')
  fd.append('file', file)
  if (config.host.indexOf('http:') > -1) {
    var protocol = window.location.protocol || 'http:'
    var subUrl = config.host.substring(5, config.host.length)
    config.host = protocol + subUrl
  }
  // 数据组装完成后，发送上传请求到阿里云oss
  axios.request({
    url: config.host,
    method: 'POST',
    data: fd,
    // 这里，我们可以做上传经度
    onUploadProgress: function(progressEvent:any) {
      if (progressEvent.lengthComputable) {
        let percent = (progressEvent.loaded / progressEvent.total) * 100 || 0
        progressCallback({
          percent: percent
        })
      }
    }
  })
    .then(() => {
    // 拿到结果后，做其他操作
      let size = file.size > 1000000 ? (file.size / 1000000).toFixed(2) + 'M' : (file.size / 1000).toFixed(2) + 'KB'
      successCallback({
        attachment: fileName,
        aliyunAddress: key,
        size: size,
        host: config.host
      })
    })
    .catch(err => {
      errCallBack(err)
    }).catch(err => {
  errCallBack(err)
})


}




export default {
  uploadAuthorityFile,
  uploadImage,
    upload,
    url(data:string){
      return request.post("/ossFile/url",data)
    },
    checkFileExist,
    ossParameter
  }



  